import type { App } from "vue";

// 动态改变元素宽高
const vVarWidth = {
  mounted: (el: HTMLElement, binding: any) => {
    let value = 0;
    let baseValue = 0;
    if (binding.value && !Number.isNaN(binding.value - 0)) {
      value = binding.value;
    }
    console.log(binding.modifiers);
    
    if (binding.modifiers.percent) {
      // 基础值是百分比
      baseValue = Number(el.dataset.widthBase!.replace("%", ""));
      if (baseValue && !Number.isNaN(baseValue)) {
        // 加入 setTimeout 是配合动画效果
        setTimeout(() => {
          // 通过基础值和百分比球的实际宽高值
          if (binding.arg === "w") {
            el.style.width = (baseValue / 100) * value + "%";
          }
          if (binding.arg === "h") {
            el.style.height = (baseValue / 100) * value + "%";
          }
          if (binding.arg === "w&h" || binding.arg === "h&w") {
            el.style.width = (baseValue / 100) * value + "%";
            el.style.height = (baseValue / 100) * value + "%";
          }
        }, 50);
      }
    } else {
      // 基础值不是百分比，而是固定的 px 值
      // 确定基础值
      if (
        el.dataset.widthBase &&
        !Number.isNaN((el.dataset.widthBase as any) - 0)
      ) {
        baseValue = el.dataset.widthBase as any;
      }
      // 加入 setTimeout 是配合动画效果
      setTimeout(() => {
        // 通过基础值和百分比球的实际宽高值
        if (binding.arg === "w") {
          el.style.width = (value / 100) * baseValue + "px";
        }
        if (binding.arg === "h") {
          el.style.height = (value / 100) * baseValue + "px";
        }
        if (binding.arg === "w&h" || binding.arg === "h&w") {
          el.style.width = (value / 100) * baseValue + "px";
          el.style.height = (value / 100) * baseValue + "px";
        }
      }, 50);
    }
  },
};

export function setWidthChange(app: App) {
  app.directive("dyxChangeWh", vVarWidth);
}
